package edu.hawaii.ics314.ical.controller;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;

import edu.hawaii.ics314.ical.model.Calendar;
import edu.hawaii.ics314.ical.model.Calendars;
import edu.hawaii.ics314.ical.model.CalendarComponent.ComponentPriority;
import edu.hawaii.ics314.ical.view.ViewEvent;
import edu.hawaii.ics314.ical.view.ViewListener;

public class CheckInThreeViewController implements ViewListener<String> {
	
	private final ComponentPriority MIN_PRIORITY_THRESHOLD;
	
	public CheckInThreeViewController(ComponentPriority minPriorityThreshold) {
		MIN_PRIORITY_THRESHOLD = minPriorityThreshold;
	}
	
	@Override
	public void onViewResult(ViewEvent<String> evt) {
		// Isolate individual file names and remove whitespace.
		String[] fileNames = evt.getResult().split(",");
		if(fileNames.length < 2) {
			System.out.println("You must specify at least two valid path names.");
			evt.getSource().show();
			return;
		}
		for(int i = 0; i < fileNames.length; i++) {
			fileNames[i] = fileNames[i].trim();
		}
		// Deserialize into Calendar objects.
		ArrayList<Calendar> calendars = new ArrayList<Calendar>();
		for(int i = 0; i < fileNames.length; i++) {
			try {
				calendars.add(Calendar.fromFile(new File(fileNames[i])));
			} catch (IOException | ParseException e) {
				System.out.printf("An error occurred while reading file '%s': %s%n%nError Detail:%n", 
						fileNames[i], e.getMessage());
				e.printStackTrace(System.out);
			}
		}
		if(calendars.size() < 2) {
			System.out.println("You must specify at least two valid path names.");
			evt.getSource().show();
			return;
		}
		// Find common free times. 
		Calendar commonFreeTimes = Calendars.freeTime(calendars.get(0), MIN_PRIORITY_THRESHOLD);
		for(int i = 1; i < calendars.size(); i++) {
			Calendar curCalFreeTimes = Calendars.freeTime(calendars.get(i), MIN_PRIORITY_THRESHOLD);
			commonFreeTimes = Calendars.intersection(commonFreeTimes, curCalFreeTimes);
		}
		// Write out the common free times calendar.
		String fileNamesList = Arrays.asList(fileNames).toString(); // Get comma-separated list.
		fileNamesList = fileNamesList.substring(1, fileNamesList.length() - 1); // Remove enclosing brackets.
		File outputCalFile = new File("Possible Meeting Times - " + fileNamesList + ".ics");
		try {
			outputCalFile.createNewFile();
			commonFreeTimes.toFile(outputCalFile);
			System.out.println("Wrote .ics file: " + outputCalFile.getAbsolutePath());
		} catch (IOException e) {
			System.out.printf("An error occurred while writing file '%s': %s%n%nError Detail:%n", 
					outputCalFile.getAbsolutePath(), e.getMessage());
			e.printStackTrace(System.out);
		}
	}

}
